package com.oracle.lingshangejia.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.bean.LoginBean;
import com.oracle.lingshangejia.bean.ThreeDoctorBean;
import com.oracle.lingshangejia.mvp.base.BaseActivity;
import com.oracle.lingshangejia.utils.AppStateUtils;
import com.oracle.lingshangejia.utils.LastClickUtils;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;
import com.oracle.lingshangejia.view.CustomRadioButton;
import java.util.HashMap;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


//重构代码中  更换基类
@RuntimePermissions
public class LoginActivity extends BaseActivity implements View.OnClickListener,RadioGroup.OnCheckedChangeListener {
    private EditText et_phone;
    private ImageView iv_login_del;
    private EditText et_pass;
    private RelativeLayout rl_login_ok;
    private ImageView iv_pass_del;
    private RadioGroup rg_radiogroup;
    private CustomRadioButton crb_threedoctors;
    private CustomRadioButton crb_communitydoctor;
    private int mark=1;
    private LoginBean bean;
    private ThreeDoctorBean threeDoctorBean;
    private String mPhone;
    private String mPass;


    @Override
    public int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {
        et_phone=findViewById(R.id.et_phone);
        rg_radiogroup=findViewById(R.id.rg_radiogroup);
        iv_login_del=findViewById(R.id.iv_login_del);
        et_pass=findViewById(R.id.et_pass);
        iv_pass_del=findViewById(R.id.iv_pass_del);
        rl_login_ok=findViewById(R.id.rl_login_ok);
        crb_threedoctors=findViewById(R.id.crb_threedoctors);
        crb_communitydoctor=findViewById(R.id.crb_communitydoctor);
        rl_login_ok.setOnClickListener(this);
        iv_login_del.setOnClickListener(this);
        iv_pass_del.setOnClickListener(this);
        rg_radiogroup.setOnCheckedChangeListener(this);
        initListener();
        LoginActivityPermissionsDispatcher.loginPermissinWithCheck(LoginActivity.this);
    }
    //设置监听器
    private void initListener(){
        et_phone.addTextChangedListener(textWatcher);
        et_pass.addTextChangedListener(textWatcher1);
        iv_login_del.setOnClickListener(this);
    }

    @NeedsPermission({Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE
    ,Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA})
   void loginPermissin(){

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_phone.getEditableText().length() >= 1){
                iv_login_del.setVisibility(View.VISIBLE);
            } else{
                iv_login_del.setVisibility(View.GONE);
            }
        }
    };
    private TextWatcher textWatcher1 = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_pass.getEditableText().length() >= 1){
                iv_pass_del.setVisibility(View.VISIBLE);
            } else{
                iv_pass_del.setVisibility(View.GONE);
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_login_ok:
                mPhone = et_phone.getText().toString().trim();
                mPass = et_pass.getText().toString().trim();
                if(TextUtils.isEmpty(mPhone)){
                    Toast.makeText(LoginActivity.this,"请输入手机号",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(mPass)){
                    Toast.makeText(LoginActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (LastClickUtils.isLastClick("点的太快了哦")){
                   getNetLogin(mPhone, mPass);
                }
                break;
            case R.id.iv_login_del:
                et_phone.setText("");
                break;
            case R.id.iv_pass_del:
                et_pass.setText("");
                break;
        }
    }
    /**
     * 登录
     */
    private void getNetLogin(String username,String password) {
        showLoading();
        HashMap<String,Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        map.put("mark",mark);
        map.put("imei",AppStateUtils.getIMEI(this));
        map.put("ipAddress",AppStateUtils.getIPAddress(this));
        map.put("phoneModel",AppStateUtils.getDeviceBrand());
        map.put("systemVersion",AppStateUtils.getSystemVersion());
        map.put("appVersion",AppStateUtils.getVerName(this));



        OkHttpUtils.getNetLoginWork(this, Constant.baseurl+"open/login",map,handler);
    }
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismissLoading();
            switch (msg.what){
                case 1:

                    try{
                        String s = (String) msg.obj;
                        Gson gson=new Gson();
                        if(mark==1){  //社区医生登录
                            bean=gson.fromJson(s, LoginBean.class);
                            if(bean.getCode()==0){
                                Intent it=new Intent(LoginActivity.this, MainActivity.class);//启动MainActivity

                                Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                SpUtils.put(LoginActivity.this,"token",bean.getUser().getToken());
                                SpUtils.put(LoginActivity.this,"ysid",bean.getUser().getUserId());
                                SpUtils.put(LoginActivity.this,"isLogin",true);
                                SpUtils.put(LoginActivity.this,"mark",1);
                                SpUtils.put(LoginActivity.this,"name" , bean.getUser().getName());
                                SpUtils.put(LoginActivity.this,"s_phone",bean.getUser().getUsername());
                                startActivity(it);
                                finish();
                            }else{
                                Toast.makeText(LoginActivity.this,bean.getMsg(),Toast.LENGTH_SHORT).show();
                            }
                        }else{  //三甲医生登录
                            threeDoctorBean=gson.fromJson(s,ThreeDoctorBean.class);
                            if(threeDoctorBean.getCode()==0){
                                Intent it=new Intent(LoginActivity.this, ThreeDoctorMainActivity.class);
                                // it.putExtra("mark",mark);
                                it.putExtra("ysid",threeDoctorBean.getSjyyys().getId());
                                Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                SpUtils.put(LoginActivity.this,"token",threeDoctorBean.getSjyyys().getToken());
                                SpUtils.put(LoginActivity.this,"isLogin",true);
                                SpUtils.put(LoginActivity.this,"mark",2);
                                SpUtils.put(LoginActivity.this,"userid",threeDoctorBean.getSjyyys().getId());
                                SpUtils.put(LoginActivity.this,"sj_phone",threeDoctorBean.getSjyyys().getPhone());
                                startActivity(it);
                                finish();
                               // MyApp.the().getmAgoraAPI().login2(appId, threeDoctorBean.getSjyyys().getPhone(), "_no_need_token", 0, "", 5, 1);
                            }else{
                                Toast.makeText(LoginActivity.this,threeDoctorBean.getMsg(),Toast.LENGTH_SHORT).show();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(LoginActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(LoginActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(LoginActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == crb_threedoctors.getId()){  //选择了三甲医生
            mark=2;
        }else if(checkedId == crb_communitydoctor.getId()){ //选择了居民医生
            mark=1;
        }
    }
}
